//
//  ForgetPasswordVC.m
//  MyNewProject
//
//  Created by 王春辉 on 2020/2/25.
//  Copyright © 2020 sun. All rights reserved.
//

#import "ForgetPasswordVC.h"
#import "CQCountDownButton.h"
#import "SVProgressHUD.h"
#import "WJBaseModel.h"

@interface ForgetPasswordVC ()<UITextFieldDelegate>
@property (nonatomic, strong) CQCountDownButton *countDownButton;
@property (nonatomic, strong) UITextField *mobileTf;
@property (nonatomic, strong)UITextField *yanTf;
@property (nonatomic, strong)UITextField *xinPasTf ;
@property (nonatomic, strong)UITextField *sureNewPasTf ;
@property (nonatomic, strong)UIButton *sureBtn ;
@property (nonatomic, strong) UITextField * currentTextField;
@property (nonatomic, strong) UIScrollView *myScroll;
@end

@implementation ForgetPasswordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle = @"忘记密码";
    [self initView];
}
-(void)keboardDismiss:(UIGestureRecognizer*)gesture
{
    [self.view endEditing:YES];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    self.currentTextField = textField;
    return true;
}
-(void)initView
{
    UIScrollView *bgScrollView = [[UIScrollView alloc] init];
    bgScrollView.backgroundColor = SKRGBColor(241, 241, 241);
    [self.view addSubview:bgScrollView];
    self.myScroll = bgScrollView;
    
    bgScrollView.sd_layout
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .bottomEqualToView(self.view)
    .topSpaceToView(self.view, SKTopBar_Height);
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keboardDismiss:)];
    [bgScrollView addGestureRecognizer:tapGesture];
    UITextField *promptLab = [[UITextField alloc] init];
    promptLab.backgroundColor = SKColorWithHex(0xFFFFFF);
    promptLab.placeholder = @"请输入您的电话号码";
    promptLab.textColor = SKColorWithHex(0x444444);
    promptLab.font = SKFONT_Medium(15);
    self.mobileTf = promptLab;
    UIView *le = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 46)];
    promptLab.leftView = le;
    promptLab.leftViewMode = UITextFieldViewModeAlways;
    [bgScrollView addSubview:promptLab];
    promptLab.sd_layout
    .leftEqualToView(bgScrollView)
    .rightEqualToView(bgScrollView)
    .topSpaceToView(bgScrollView, 10)
    .heightIs(46);



    UILabel *YanPromptLab = [[UILabel alloc] init];
    YanPromptLab.text = @"验证码";
    YanPromptLab.textColor = SKColorWithHex(0x999999);
    YanPromptLab.font = SKFONT_Medium(15);
    [bgScrollView addSubview:YanPromptLab];
    YanPromptLab.sd_layout
    .leftSpaceToView(bgScrollView, 20)
    .topSpaceToView(promptLab, 0)
    .heightIs(34)
    .widthIs(100);


    [self countCutDown:bgScrollView];

    self.countDownButton.sd_layout
//    .leftSpaceToView(bgScrollView, 20)
    .rightSpaceToView(bgScrollView, 0)
    .topSpaceToView(YanPromptLab, 0)
    .heightIs(46)
    .widthIs(110);
//    self.countDownButton.frame = CGRectMake(pWTextField.right+10, pWTextField.top,SCREEN_WIDTH -pWTextField.width -10 - 43*2, 40);

    SKWeakSelf;

    UITextField *yanTf = [[UITextField alloc] init];
    yanTf.delegate = self;
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes: @{NSForegroundColorAttributeName:SKColorWithHex(0x444444),NSFontAttributeName:SKFONT_Medium(15)}];
    yanTf.attributedPlaceholder = attrString;
    yanTf.backgroundColor = [UIColor whiteColor];
    yanTf.textColor = SKColorWithHex(0x444444);
    yanTf.font = SKFONT_Medium(15);
    [bgScrollView addSubview:yanTf];
    UIView *yanLeftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 46)];
    yanTf.leftView = yanLeftView;
    yanTf.leftViewMode = UITextFieldViewModeAlways;
    yanTf.sd_layout
    .leftEqualToView(bgScrollView)
    .topSpaceToView(YanPromptLab, 0)
    .rightSpaceToView(bgScrollView, 110)
    .heightIs(46);
    
    UILabel *newPasPromptLab = [[UILabel alloc] init];
    newPasPromptLab.text = @"新密码";
    newPasPromptLab.textColor = SKColorWithHex(0x999999);
    newPasPromptLab.font = SKFONT_Medium(15);
    newPasPromptLab.textColor = [UIColor grayColor];
    [bgScrollView addSubview:newPasPromptLab];
    newPasPromptLab.sd_layout
    .leftSpaceToView(bgScrollView, 20)
    .topSpaceToView(yanTf, 0)
    .heightIs(34)
    .widthIs(100);
    
    
    UITextField *newPasTf = [[UITextField alloc] init];
    newPasTf.delegate = self;
    NSAttributedString *newPasAttrString = [[NSAttributedString alloc] initWithString:@"请输入新密码" attributes: @{NSForegroundColorAttributeName:SKColorWithHex(0x444444),NSFontAttributeName:SKFONT_Medium(15)}];
    newPasTf.textColor = SKColorWithHex(0x444444);
    newPasTf.font = SKFONT_Medium(15);
    newPasTf.attributedPlaceholder = newPasAttrString;

    newPasTf.backgroundColor = [UIColor whiteColor];
    [bgScrollView addSubview:newPasTf];
    UIView *newPasLeftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 46)];
    newPasTf.leftView = newPasLeftView;
    newPasTf.leftViewMode = UITextFieldViewModeAlways;
    newPasTf.sd_layout
    .leftEqualToView(bgScrollView)
    .topSpaceToView(newPasPromptLab, 0)
    .rightEqualToView(bgScrollView)
    .heightIs(46);
    
    UITextField *sureNewPasTf = [[UITextField alloc] init];
    sureNewPasTf.delegate = self;
    NSAttributedString *sureNewPasAttrString = [[NSAttributedString alloc] initWithString:@"请确认新密码" attributes: @{NSForegroundColorAttributeName:SKColorWithHex(0x444444),NSFontAttributeName:SKFONT_Medium(15)}];
    sureNewPasTf.textColor = SKColorWithHex(0x444444);
    sureNewPasTf.font = SKFONT_Medium(15);
    sureNewPasTf.attributedPlaceholder = sureNewPasAttrString;
    sureNewPasTf.backgroundColor = [UIColor whiteColor];
    [bgScrollView addSubview:sureNewPasTf];
    UIView *sureNewPasLeftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 46)];
    sureNewPasTf.leftView = sureNewPasLeftView;
    sureNewPasTf.leftViewMode = UITextFieldViewModeAlways;
    sureNewPasTf.sd_layout
    .leftEqualToView(bgScrollView)
    .topSpaceToView(newPasTf, 1)
    .rightEqualToView(bgScrollView)
    .heightIs(46);
    
    
    UIButton *sureBtn = [[UIButton alloc] init];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn addTarget:self action:@selector(confirmEvent:) forControlEvents:UIControlEventTouchUpInside];
    sureBtn.backgroundColor = SKColorWithHex(0xE33030);
    [bgScrollView addSubview:sureBtn];
    sureBtn.sd_layout
    .leftSpaceToView(bgScrollView, 20)
    .rightSpaceToView(bgScrollView, 20)
    .bottomSpaceToView(bgScrollView, 100)
    .heightIs(50);


    self.yanTf = yanTf;
    self.xinPasTf = newPasTf;
    self.sureNewPasTf = sureNewPasTf;
    self.sureBtn = sureBtn;
    self.xinPasTf.secureTextEntry = true;
    self.sureNewPasTf.secureTextEntry = true;
}
-(void)confirmEvent:(UIButton*)sender
{
    if (IsStrEmpty(self.yanTf.text)) {
        [self.view makeToast:@"验证码不能为空" duration:1 position:CSToastPositionCenter];
        return;
    }
    if (IsStrEmpty(self.xinPasTf.text)) {
        [self.view makeToast:@"新密码不能为空" duration:1 position:CSToastPositionCenter];
        return;
    }
    if (IsStrEmpty(self.sureNewPasTf.text)) {
        [self.view makeToast:@"新密码不能为空" duration:1 position:CSToastPositionCenter];
        return;
    }
    if (![self.sureNewPasTf.text isEqualToString:self.xinPasTf.text]) {
        [self.view makeToast:@"密码不一致" duration:1 position:CSToastPositionCenter];
        return;
    }
    NSDictionary *param = @{@"code":self.yanTf.text,
                            @"password":self.sureNewPasTf.text,
                            @"mobile":self.mobileTf.text};
    SKWeakSelf;
    [YQNetworking postWithUrl:@"my/losePassword" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        WJBaseModel *model = [WJBaseModel modelWithDictionary:response];
        if ([model isSuccess]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:model.msg preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                [weakSelf.navigationController popViewControllerAnimated:true];
            }];
            [alert addAction:sure];
            [self presentViewController:alert animated:true completion:nil];
        }else {
            [weakSelf showMessage:model.msg];
        }
    } failBlock:^(NSError *error) {
        
    }];
}
-(void)countCutDown:(UIScrollView*)bgScrollView
{
    SKWeakSelf;
    self.countDownButton = [[CQCountDownButton alloc] initWithDuration:10 buttonClicked:^{
        if (self.mobileTf.text && (self.mobileTf.text.length == 11)) {
            NSLog(@"按钮点击");
            //------- 按钮点击 -------//
            [SVProgressHUD showWithStatus:@"正在获取验证码..."];
            [YQNetworking postWithUrl:@"Login/sendsms" refreshRequest:YES cache:NO params:@{@"mobile":self.mobileTf.text,@"sign":@"yupinyouxuan*****yupinyouxuan"} progressBlock:^(int64_t bytesRead, int64_t totalBytes) {

            } successBlock:^(id response) {

                NSDictionary *dic = (NSDictionary*)response;
                if ([dic[@"status"] isEqualToString:@"ok"])
                {
                    [SVProgressHUD showSuccessWithStatus:@"验证码已发送"];
                    [weakSelf.countDownButton startCountDown];


                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:@"获取失败，请重试"];
                    weakSelf.countDownButton.enabled = YES;

                }
            } failBlock:^(NSError *error) {

            }];
            // 请求数据
        }else {
            
        }
    } countDownStart:^{
        //------- 倒计时开始 -------//
        NSLog(@"倒计时开始");
    } countDownUnderway:^(NSInteger restCountDownNum) {
        //------- 倒计时进行中 -------//
        [weakSelf.countDownButton setTitle:[NSString stringWithFormat:@"重新获取(%ld)", restCountDownNum] forState:UIControlStateNormal];
    } countDownCompletion:^{
        //------- 倒计时结束 -------//
        [weakSelf.countDownButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        NSLog(@"倒计时结束");
    }];
    //------- 按钮的属性设置 -------//
    [self.countDownButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.countDownButton setTitleColor:SKColorWithHex(0x4444444) forState:UIControlStateNormal];
    [self.countDownButton setTitleColor:SKColorWithHex(0x999999) forState:UIControlStateDisabled];
    self.countDownButton.backgroundColor = [UIColor whiteColor];
    self.countDownButton.titleLabel.font = SKFONT_Medium(15);
    [bgScrollView addSubview:self.countDownButton];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    [self hideNavLine];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification {

    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];


    CGRect textFieldRect  = [self.view convertRect:self.currentTextField.frame fromView:self.myScroll];


    SKLog(@"%f",textFieldRect.origin.y+ textFieldRect.size.height - keyboardRect.origin.y);
    if (self.currentTextField.bottom+ SKTopBar_Height - keyboardRect.origin.y > 0) {

        self.myScroll.top =-(self.currentTextField.bottom+SKTopBar_Height - keyboardRect.origin.y);
        //        [self.myScroll setContentOffset:CGPointMake(0, (self.currentTextField.bottom - keyboardRect.origin.y) + SKTopBar_Height) animated:YES];
        [self.myScroll scrollRectToVisible:self.currentTextField.frame animated:YES];

    }

}

- (void)keyboardWillHide:(NSNotification *)notification {
    //    [self.myScroll setContentOffset:CGPointMake(0, 0) animated:YES];

    self.myScroll.top =SKTopBar_Height;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
